package cn.nubia.admin.sysconfig.service;

import cn.nubia.admin.common.mybatis.bean.Paged;
import cn.nubia.admin.common.mybatis.bean.Query;
import cn.nubia.admin.common.mybatis.service.BaseServiceImpl;
import cn.nubia.admin.common.utils.BeanUtils;
import cn.nubia.admin.sysconfig.bean.MenuResource;
import cn.nubia.admin.sysconfig.bean.SystemLog;
import cn.nubia.admin.sysconfig.dto.MenuResourceDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by Jason on 2015/6/27.
 * 菜单权限服务.
 */
@Service
public class MenuResourceService extends BaseServiceImpl<MenuResource> {

    @Autowired
    SystemLogService systemLogService;

    /**
     * 获取所有可用的资源列表.
     *
     * @return 可用的资源列表.
     */
    public Paged<MenuResource> getMenuResourcePage(Integer pageNo, Integer pageSize) {
        Query<MenuResource> query = Query.build(MenuResource.class);
        //设置可用的.
        query.addEq("enable", 0);
        query.addOrder("permission" , Query.DBOrder.ASC);
        query.setPaged(pageNo , pageSize);
        return findPagedByQuery(query);
    }

    /**
     * 获取所有可用的资源列表.
     *
     * @return 可用的资源列表.
     */
    public List<MenuResource> getMenuResourceList() {
        Query<MenuResource> query = Query.build(MenuResource.class);
        //设置可用的.
        query.addEq("enable", 0);
        return findByQuery(query);
    }


    /**
     * 保存或者修改资源.
     *
     * @param menuResource 资源
     * @return 成功标志
     */
    public boolean save(MenuResource menuResource) {
        menuResource.setUpdateTime(new Date());
        if (null == menuResource.getId()) {
            insert(menuResource);
            systemLogService.log(SystemLog.ModuleTypeEnum.MENURESOURCELIST, SystemLog.OperateTypeEnum.ADD, menuResource.getId());

        } else {
            update(menuResource);

            systemLogService.log(SystemLog.ModuleTypeEnum.MENURESOURCELIST, SystemLog.OperateTypeEnum.EDIT, menuResource.getId());

        }
        return true;
    }


    public MenuResourceDTO getResource(Integer resourceId) {
        MenuResourceDTO dto = new MenuResourceDTO();
        MenuResource menuResource = get(resourceId);
        if (null != menuResource ) {
            BeanUtils.copyProperties(menuResource, dto);
            if (menuResource.getPid() != 0) {
                MenuResource pMenu = get(menuResource.getPid());
                dto.setpName(pMenu.getName());
            }
        }
        return dto;
    }

    public List<MenuResource> getMenuResourceRootList() {
        Query<MenuResource> query = Query.build(MenuResource.class);
        //设置可用的.
        query.addEq("enable", 0);
        query.addEq("pid", 0);
        return findByQuery(query);
    }
}
